const Router = require("@koa/router");
const router = new Router();
const jwt = require("jsonwebtoken");
const {Sequelize, DataTypes, where} = require("sequelize");
// 验证用户身份的中间件
const authenticateUser = async (ctx, next) => {
  const token = ctx.headers.authorization;

  if (!token) {
    ctx.status = 401;
    ctx.body = {error: "未提供身份验证令牌。"};
    return;
  }

  // 解码 base64 编码的 token
  const decodedToken = Buffer.from(token, "base64").toString("utf-8");

  jwt.verify(decodedToken, "token", (err, decoded) => {
    if (err) {
      ctx.status = 401;
      ctx.body = {error: "无效的身份验证令牌。"};
      return;
    }

    ctx.state.userId = decoded.userId;
  });

  await next();
};

// 获取菜单列表
router.post("/getmenu", authenticateUser, async (ctx) => {
  try {
    // 从请求体中获取条件查询参数和页码信息
    const {
      dishName,
      price,
      isAvailable,
      remainingQuantity,
      SoupName,
      page = 1,
    } = ctx.request.body;

    // 构建查询条件对象
    const whereClause = {};

    // 添加每个条件的 LIKE 查询
    if (dishName) {
      whereClause.dishName = {[Sequelize.Op.like]: `%${dishName}%`};
    }
    if (price) {
      whereClause.price = {[Sequelize.Op.like]: `%${price}%`};
    }
    if (SoupName) {
      whereClause.SoupName = {[Sequelize.Op.like]: `%${SoupName}%`};
    }
    if (isAvailable) {
      whereClause.isAvailable = {[Sequelize.Op.like]: `%${isAvailable}%`};
    }
    if (remainingQuantity) {
      whereClause.remainingQuantity = {
        [Sequelize.Op.like]: `%${remainingQuantity}%`,
      };
    }

    // 计算查询偏移量
    const offset = (page - 1) * 10;

    // 查询符合条件的菜单列表，并按 createdAt 时间倒序排列
    const menuList = await ctx.state.Menu.findAll({
      where: whereClause,
      order: [["createdAt", "DESC"]], // 按 createdAt 时间倒序排列
      limit: 10,
      offset: offset,
    });

    // 查询数据总数
    const total = await ctx.state.Menu.count({
      where: whereClause,
    });

    ctx.status = 200;
    ctx.body = {menuList, total};
  } catch (error) {
    console.error("Error fetching menu:", error);
    ctx.status = 500;
    ctx.body = {error: "获取菜单时发生错误。"};
  }
});

// 添加菜单项
router.post("/add", authenticateUser, async (ctx) => {
  try {
    // 获取请求体中的菜单信息
    const {
      id,
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    } = ctx.request.body;

    // 检查是否存在同名菜品
    const existingMenu = await ctx.state.Menu.findOne({
      where: {dishName},
    });

    // 如果存在同名菜品，则提示不能添加
    if (existingMenu) {
      await update(ctx);
      return;
    }

    // 创建菜单项
    const newMenu = await ctx.state.Menu.create({
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    });

    ctx.status = 201;
    ctx.body = {message: "菜单项添加成功。", menu: newMenu};
  } catch (error) {
    console.error("Error adding menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "添加菜单项时发生错误。"};
  }
});

async function update(ctx) {
  try {
    // 查找要修改的菜单项
    const {
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    } = ctx.request.body;
    const menuId = ctx.request.body.id;

    const menuToUpdate = await ctx.state.Menu.findOne({
      where: {
        id: menuId, // 排除当前菜单项的ID
      },
    });

    if (!menuToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的菜单项。"};
      return;
    }

    // 检查是否存在其他具有相同菜名的菜单项
    const existingMenu = await ctx.state.Menu.findOne({
      where: {
        dishName,
        id: {[Sequelize.Op.not]: menuId}, // 排除当前菜单项的ID
      },
    });

    if (existingMenu) {
      ctx.status = 400;
      ctx.body = {error: "已存在相同菜名的菜单项，请选择其他菜名。"};
      return;
    }

    // 修改菜单项
    await menuToUpdate.update({
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    });

    ctx.status = 200;
    ctx.body = {message: "菜单项修改成功。", menu: menuToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "修改菜单项时发生错误。"};
  }
}

// 修改菜单项
router.post("/update", authenticateUser, async (ctx) => {
  try {
    // 获取请求体中的菜单信息
    const {
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    } = ctx.request.body;
    const menuId = ctx.request.body.id;

    // 查找要修改的菜单项
    const menuToUpdate = await ctx.state.Menu.findOne({
      where: {
        id: menuId, // 排除当前菜单项的ID
      },
    });

    if (!menuToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的菜单项。"};
      return;
    }

    // 检查是否存在其他具有相同菜名的菜单项
    const existingMenu = await ctx.state.Menu.findOne({
      where: {
        dishName,
        id: {[Sequelize.Op.not]: menuId}, // 排除当前菜单项的ID
      },
    });

    if (existingMenu) {
      ctx.status = 400;
      ctx.body = {error: "已存在相同菜名的菜单项，请选择其他菜名。"};
      return;
    }

    // 修改菜单项
    await menuToUpdate.update({
      dishName,
      price,
      image,
      isAvailable,
      remainingQuantity,
      SoupName,
      Unitname,
    });

    ctx.status = 200;
    ctx.body = {message: "菜单项修改成功。", menu: menuToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "修改菜单项时发生错误。"};
  }
});

// 下架菜单项
router.post("/Shelf", authenticateUser, async (ctx) => {
  try {
    // 获取请求体中的菜单信息

    const menuId = ctx.request.body.id;

    // 查找要修改的菜单项
    const menuToUpdate = await ctx.state.Menu.findOne({
      where: {
        id: menuId, // 排除当前菜单项的ID
      },
    });

    if (!menuToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "未找到要修改的菜单项。"};
      return;
    }

    // 下架菜单项
    await menuToUpdate.update({
      isAvailable: false,
    });

    ctx.status = 200;
    ctx.body = {message: "菜单项下架成功。", menu: menuToUpdate};
  } catch (error) {
    console.error("Error editing menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "菜单项下架时发生错误。"};
  }
});

// 删除菜单项
router.post("/delete/:id", authenticateUser, async (ctx) => {
  try {
    const menuId = ctx.params.id;

    // 查找要删除的菜单项
    const menuToDelete = await ctx.state.Menu.findByPk(menuId);

    // 删除菜单项
    await menuToDelete.destroy();

    ctx.status = 200;
    ctx.body = {message: "菜单项删除成功。"};
  } catch (error) {
    console.error("Error deleting menu item:", error);
    ctx.status = 500;
    ctx.body = {error: "删除菜单项时发生错误。"};
  }
});

module.exports = router;
